package br.com.comanda.service;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;
import br.com.comanda.restclient.RestClient;
import br.com.comanda.util.WebServiceUtil;
import br.com.comanda.vos.Board;

public class BoardService {

	public List<Board> readAllBoards() {
		RestClient client = new RestClient();
		String result = client.getRESTFileContent(WebServiceUtil.URL + "boards");

		List<Board> boardList = new ArrayList<Board>();
		try {
			JSONObject boardResult = new JSONObject(result);
			JSONArray boardsJson = boardResult.getJSONArray("board");

			JSONObject boardJson = null;
			Board board = null;
			for (int i = 0; i < boardsJson.length(); i++) {
				boardJson = new JSONObject(boardsJson.getString(i));

				board = new Board();
				board.setId(boardJson.getInt("id"));
				board.setBoard(boardJson.getString("board"));

				boardList.add(board);
			}

			return boardList;

		} catch (JSONException e) {
			Log.e("RESTCLIENT", "ERRO no parsing do JSON");
		}

		return null;
	}

	public void insertBoard() {
		try {
			URL url = new URL("http://192.168.0.182:8080/projeto-comanda-webservice/boards");

			HttpURLConnection conexao = (HttpURLConnection) url.openConnection();
			conexao.setRequestMethod("POST");
			conexao.addRequestProperty("Content-type", "application/json");

			conexao.setDoOutput(true);

			conexao.connect();

			OutputStream os = conexao.getOutputStream();
			os.write(board().toString().getBytes());
			os.flush();

			InputStream is = conexao.getInputStream();
			Log.i("RESTCLIENT POST", is.toString());

		} catch (IOException e) {
			Log.i("RESTCLIENT POST", e.getMessage());
		}
	}

	private JSONObject board() {
		JSONObject json = new JSONObject();

		try {
			json.accumulate("id", "");
			json.accumulate("board", "mesa rei");
		} catch (Exception e) {
			Log.i("RESTCLIENT GET BOARD", e.getMessage());
		}
		return json;
	}
}
